package com.apes.framework.plugin.condition.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.condition.model.FieldCatalog;
import com.apes.framework.plugin.condition.model.FieldCatalogItem;
import com.apes.framework.plugin.condition.repository.FieldCatalogItemRepository;
import com.apes.framework.plugin.condition.repository.FieldCatalogRepository;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字段目录
 *
 * @author wuq
 * @create 2018-11-13 12:01
 */
@Service
public class FieldCatalogService extends DomainService {

    @Autowired
    FieldCatalogRepository fieldCatalogRepository;

    @Autowired
    FieldCatalogItemRepository fieldCatalogItemRepository;

    public FieldCatalog save(SimpleRequest request){
        FieldCatalog fieldCatalog = request.getO(FieldCatalog.class);
        return fieldCatalogRepository.saveAndFlush(fieldCatalog);
    }

    public void checkData(SimpleRequest request) {
        String id = request.get("id");

        // 从数据库中取数，检查数据
        FieldCatalog oldFieldCatalog = fieldCatalogRepository.findOne(id);
        if (oldFieldCatalog == null) throw new RuntimeException("条件字段【" + id + "】在系统中不存在。");
    }

    public FieldCatalog update(SimpleRequest request){
        checkData(request);
        FieldCatalog fieldCatalog = request.getO(FieldCatalog.class);
        return fieldCatalogRepository.saveAndFlush(fieldCatalog);
    }

    public String delete(SimpleRequest request){
        checkData(request);
        FieldCatalog fieldCatalog = request.getO(FieldCatalog.class);
        fieldCatalogRepository.delete(fieldCatalog);
        return "删除成功";
    }

    public Map findFilter(SimpleRequest request) {
        Map map = request.getMap();
        List<Map<String, Object>> rows = new ArrayList<>();
        if (map.containsKey("condition")) {
            rows = (List<Map<String, Object>>) map.get("condition");
        }
        Map row = new HashMap();
        row.put("field", "id");
        row.put("value", "general");
        row.put("operator", "NE");
        rows.add(row);
        map.put("condition",rows);
        return map;
    }

    public List<FieldCatalogItem> findAllFieldCatalogItemByFieldCatalog(SimpleRequest request){
        String fieldCatalogId = request.get("fieldCatalogId");
        return fieldCatalogItemRepository.findAllByFieldCatalog_Id(fieldCatalogId);
    }
}
